<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>pdf文件转canvas</title>
</head>

<body>
	<div id="canvas"></div>
	<script type="text/javascript" src="js/jquery-3.2.0.min.js"></script>
	<script type="text/javascript" src="js/pdf.js"></script>
	<script type="module">
		
		//创建canvas元素
		function createPdfContainer(id, className) {
			var pdfContainer = document.getElementById('canvas');
			var canvasNew = document.createElement('canvas');
			canvasNew.id = id;
			canvasNew.className = className;
			pdfContainer.appendChild(canvasNew);
		};

		//建议给定pdf宽度
		function renderPDF(pdf, i, id) {
			pdf.getPage(i).then(function (page) {
				var scale = 4; //scale的值是canvas的渲染尺寸，影响清晰度
				var viewport = page.getViewport({
					scale: scale
				});
				//
				//  准备用于渲染的 canvas 元素
				//
				var canvas = document.getElementById(id);
				var context = canvas.getContext('2d');
				canvas.height = viewport.height;
				canvas.width = viewport.width;
				//
				// 将 PDF 页面渲染到 canvas 上下文中
				//
				var renderContext = {
					canvasContext: context,
					viewport: viewport
				};
				page.render(renderContext);
			});
		};

		//创建和pdf页数等同的canvas数
		function createSeriesCanvas(num, template) {
			var id = '';
			for (var j = 1; j <= num; j++) {
				id = template + j;
				createPdfContainer(id, 'pdfClass');
			}
		}

		//读取pdf文件，并加载到页面中
		function loadPDF(fileURL) {
			pdfjsLib.getDocument(fileURL).promise.then(function (pdf) {
				console.log(pdf);
				
				//用 promise 获取页面
				var id = '';
				var idTemplate = 'cw-pdf-';
				var pageNum = pdf.numPages; //pdf文件总页数
				//根据页码创建画布
				createSeriesCanvas(pageNum, idTemplate);
				$("#canvas canvas").css("width", "100%"); //canvas展示宽度
				//将pdf渲染到画布上去
				for (var i = 1; i <= pageNum; i++) {
					id = idTemplate + i;
					renderPDF(pdf, i, id);
				}
			});
		}
		//调用

		loadPDF('https://static.iquizoo.com/fat/Reports/%E4%B8%8B%E7%BA%A7%E6%9C%BA%E6%9E%84%E6%B5%8B%E8%AF%95/813289870245957/%E4%B8%80%E5%B9%B4%E7%BA%A7/1%E7%8F%AD/813299137335365/Pdf/%E3%80%90%E9%99%889%E3%80%91-%E6%8A%A5%E5%91%8A.pdf')
	</script>
</body>

</html>